package com.claude.mainactivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.claude.util.Configure;
import com.special.ResideMenuDemo.R;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.Toast;

public class UpdateActivity extends Activity {
	private MyApplication mMyApplication = null;
	private ProgressBar mProgressBar = null;
	private int mState = 0;
	private HandleMessage mHandleMessage = null;
	private int mTotal = 0;
	private String mFilePath = Configure.getInstance()
			.getPath() + "/attendance.apk";
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.activity_update);
		this.initView();
		mHandleMessage = new HandleMessage();
		mMyApplication = (MyApplication) getApplication();
		this.downloadFile();
	}
	
	public void onStop(){
		super.onStop();
		this.finish();
	}
	
	private void initView() {
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
	}
	
	private void downloadFile(){
		new Thread() {
			public void run() {
				URL url;
				try {
					url = new URL(mMyApplication.getVersion().getUrl());
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					InputStream inputStream = conn.getInputStream();
					mTotal = conn.getContentLength();
					File downloadFile = new File(mFilePath);
					FileOutputStream outputStream = new FileOutputStream(
							downloadFile);
					int end;
					byte[] buffer = new byte[1024];
					while ((end = inputStream.read(buffer)) != -1) {
						mHandleMessage.sendEmptyMessage(0x001);
						outputStream.write(buffer, 0, end);
						mState += end;		
					}
					outputStream.close();
					inputStream.close();
					mHandleMessage.sendEmptyMessage(0x000);
				} catch (MalformedURLException e) {
				} catch (IOException e) {
				}
			}
		}.start();
	}
	
	private void installApk(){
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(new File(mFilePath)), "application/vnd.android.package-archive");
		mMyApplication.startActivity(intent);
	}

	class HandleMessage extends Handler {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0x000:
				Toast.makeText(getApplicationContext(), "下载成功！",
						Toast.LENGTH_SHORT).show();
				installApk();
				break;
			case 0x001:
				mProgressBar.setMax(mTotal);
				mProgressBar.setProgress(mState);
				break;
			}
		}
	}
	public void onDestroy() {
		super.onDestroy();
		this.finish();
	}
}
